package com.cangxuan.backend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cangxuan.backend.bean.Result;
import com.cangxuan.backend.exception.ServiceException;
import com.cangxuan.backend.service.ISMSService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.HttpURLConnection;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SMSServiceImpl implements ISMSService {

    Random random = new Random();

    RedisTemplate<String, Object> rateRedisTemplate;

    @Autowired
    public void setRateRedisTemplate(RedisTemplate<String, Object> rateRedisTemplate) {
        this.rateRedisTemplate = rateRedisTemplate;
    }

    RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void send(String mobile) {
        //频率验证
        String smsSendTime = "smsSendTime-" + mobile;
        if (rateRedisTemplate.hasKey(smsSendTime)) {
            throw new ServiceException(400, "发送频率太快");
        }
        //向redis存储发送时间
        rateRedisTemplate.opsForValue().set(smsSendTime, LocalDateTime.now(), 1, TimeUnit.MINUTES);

        //验证码范围：1000 9999
        String vCode = String.valueOf(random.nextInt(9000) + 1000);
        log.info("向" + mobile + "发送短信，验证码：" + vCode);
        //调用短信接口API，向指定mobile的手机发送短信
        JSONObject body = new JSONObject();
        body.put("mobile", mobile);
        body.put("vcode", vCode);
        Result result = restTemplate.postForObject("http://CangXuanPushService/api/sendSMS", body, Result.class);
        log.info("短信发送结果：");
        log.info(result.toString());
        if (result.getMessage().equals("OK")) {
            //短信发送成功
            //向redis存储验证码
            rateRedisTemplate.opsForValue().set("smsCode-" + mobile, vCode, 2, TimeUnit.MINUTES);
        } else {
            throw new ServiceException(402, result.getMessage());
        }
    }

}
